package com.amentretenimiento;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Calendar;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.SensorManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.OrientationEventListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ExhibicionSup extends Activity implements Runnable{
//	String urlamentretenimiento="http://201.155.80.190:8080/";
//	private String urlamentretenimiento="http://201.155.80.190:1863/";
	private String urlamentretenimiento=UsuariosSQLiteHelper.urlam;

//	String urlamentretenimiento="http://www.smartthinking.com.mx:8080/";

	SAXParserFactory spf;
	SAXParser sp;
	XMLReader xr ;
	private static final int CAMERA_PIC_REQUEST = 1337;  
	LoginSitesList loginsitesList = null,loginsitesList2 = null,loginsitesList3=null;
	Spinner spinnervideo,spinnerconsumo,spinnerretail;
	String idexhibicion,idexhibicion2,idexhibicion3, idAgente, idCia,idCliente;
	RadioButton radiovideo, radioconsumo,radioretail;
	Bitmap bm=null;
	private ProgressDialog pd;
	String hora;
	ByteArrayBody bab;
	private String nombres;
	RadioGroup group;
	private String imageInSD = Environment.getExternalStorageDirectory()+"/test.jpg";
	public Dialog dialog;
	int signal3g=0;
	
	String nombrefoto;
	String nomtiendacod;
		
	private OrientationEventListener myOrientationEventListener;
	private int orientation = 0;
	
	public void onBackPressed() {
		if(myOrientationEventListener!=null)
			myOrientationEventListener.disable();
		
		boolean internet = isInternetConnectionActive(ExhibicionSup.this);
		if (internet == true){
		Intent atras=new Intent(ExhibicionSup.this, MenuSupervisor.class);
		atras.putExtra("idagente", idAgente);
		
		atras.putExtra("idcliente", idCliente);
		  SharedPreferences preferences =  getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);;

		  Log.i("nombre promotor", preferences.getString("nombreagente", "nulo"));
		  Log.i("nombre tienda", preferences.getString("nombresucursal", "nulo"));
		atras.putExtra("nombre", preferences.getString("nombresucursal", "nulo"));
		
		atras.putExtra("miusuario",  preferences.getString("nombreagente", "nulo"));


		
		startActivity(atras);
		} else if(internet == false){
            AlertDialog alertdialog=new AlertDialog.Builder(ExhibicionSup.this).create();
			alertdialog.setIcon(R.drawable.icon);
	    	alertdialog.setTitle("Aviso");
	    	alertdialog.setMessage("Error de conectividad");
	    	alertdialog.show();
		}
		
	}
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.exhibicion);
		
//        Display display = getWindowManager().getDefaultDisplay(); 
//        int width = display.getWidth();  // deprecated
//        int height = display.getHeight();  // deprecated
//        
//        Log.i("WIDTH", ""+width);
//        Log.i("HEIGHT", ""+height);
//        
//        if(height > 1000){
//        	 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//        }
		
//		
		
		myOrientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_NORMAL){

			@Override
			public void onOrientationChanged(int arg0) {
				Log.i("Orientation: ", ""+String.valueOf(arg0));
				orientation = arg0;
				//		     textviewOrientation.setText("Orientation: " + String.valueOf(arg0));
			}
		};


		if (myOrientationEventListener.canDetectOrientation()){
			//				Toast.makeText(this, "Can DetectOrientation", Toast.LENGTH_LONG).show();
			myOrientationEventListener.enable();
		}else{
//			Toast.makeText(this, "Error", Toast.LENGTH_LONG).show();
//			finish();
		}
		
		SharedPreferences prefs =
				getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
		nomtiendacod = remove1(prefs.getString("nombre", "nulo"));	
		Log.i("CADENACODIF", ""+nomtiendacod);
		Calendar mical=Calendar.getInstance();
		String fec=""+mical.get(Calendar.DAY_OF_MONTH)+"-"+(mical.get(Calendar.MONTH)+1)+"-"+mical.get(Calendar.YEAR);
		hora=""+mical.get(Calendar.HOUR_OF_DAY)+"-"+mical.get(Calendar.MINUTE)+"-"+mical.get(Calendar.SECOND);

		nombrefoto=nomtiendacod.toUpperCase()+fec+"_"+hora+".jpeg";
		Log.i("nombre foto", ""+nombrefoto);
		
		
		
		boolean internet = isInternetConnectionActive(ExhibicionSup.this);
		if (internet == true){
			
			
			Bundle extras = getIntent().getExtras();
			if(extras!=null){
				idCia = extras.getString("idCia");
				TextView nombre = (TextView) findViewById(R.id.mueble);
				nombres=extras.getString("nombre");
//				  SharedPreferences prefs =
//						     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
				nombre.setText(prefs.getString("nombre", "nulo"));
				idAgente=extras.getString("idAgente");
				idCliente= extras.getString("idCliente");

			}

		//******* para el spinner de muebles *********//
		loginsitesList=mostrarMuebles();
		loginsitesList2=mostrarConsumo();
		loginsitesList3=mostrarRetail();

		
		String[] arrayprod, arrayconsumo,arrayretail;
		arrayprod = new String[loginsitesList.getidExhibicion().size()];
		arrayconsumo=new String[loginsitesList2.getidExhibicion().size()];
		arrayretail=new String[loginsitesList3.getidExhibicion().size()];
		
		for(int i=0; i<arrayprod.length; i++){
			
			arrayprod[i]=loginsitesList.getnombrexhibicion().get(i); 
		}
		for(int i=0; i<arrayconsumo.length; i++){
			
			arrayconsumo[i]=loginsitesList2.getnombrexhibicion().get(i); 
		}
		for(int i=0; i<arrayretail.length; i++){
			
			arrayretail[i]=loginsitesList3.getnombrexhibicion().get(i); 
		}
		
		
		spinnerconsumo=(Spinner) findViewById(R.id.spinnerconsumo);
		spinnerconsumo.setEnabled(false);
		
		spinnerretail=(Spinner) findViewById(R.id.spinnerretail);
		spinnerretail.setEnabled(false);
		
		
		spinnervideo = (Spinner) findViewById(R.id.spinner1);

		radiovideo=(RadioButton) findViewById(R.id.video);
		radioconsumo=(RadioButton)findViewById(R.id.consumo);
		radioretail=(RadioButton)findViewById(R.id.retail);
		group=(RadioGroup) findViewById(R.id.radioGroup1);
		group.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				switch (checkedId) {
				case R.id.video:
//			    	Toast.makeText(getApplicationContext(), "Video", Toast.LENGTH_LONG).show();
					spinnerconsumo.setEnabled(false);
					spinnerretail.setEnabled(false);
					spinnervideo.setEnabled(true);
					break;
					
				case R.id.consumo:
//			    	Toast.makeText(getApplicationContext(), "Consumo", Toast.LENGTH_LONG).show();
					spinnerconsumo.setEnabled(true);
					spinnervideo.setEnabled(false);
					spinnerretail.setEnabled(false);

					break;
					
				case R.id.retail:
//			    	Toast.makeText(getApplicationContext(), "Retail", Toast.LENGTH_LONG).show();
					spinnerconsumo.setEnabled(false);
					spinnervideo.setEnabled(false);
					spinnerretail.setEnabled(true);

					break;

				default:
					break;
				}
			}
		});
		
		
		ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayretail);
		adapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerretail.setAdapter(adapter3);
		
		spinnerretail.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				idexhibicion3=loginsitesList3.getidExhibicion().get(arg2);
				Log.i("IDEXHIBICIONRETAIL", ""+idexhibicion3);
//				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
		ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayconsumo);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnerconsumo.setAdapter(adapter2);
		
		spinnerconsumo.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				idexhibicion2=loginsitesList2.getidExhibicion().get(arg2);
				Log.i("IDEXHIBICIONCONSUMO", ""+idexhibicion2);
				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
	    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, arrayprod);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinnervideo.setAdapter(adapter);
		
		spinnervideo.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				idexhibicion=loginsitesList.getidExhibicion().get(arg2);
				Log.i("IDEXHIBICIONVIDEO", ""+idexhibicion);

				
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
		
		
		//termina spinner muebles

//    	Toast.makeText(getApplicationContext(), "nombre tienda: "+nombres, Toast.LENGTH_LONG).show();

		Button foto=(Button) findViewById(R.id.tomarfoto);
//		Button enviarfoto=(Button) findViewById(R.id.enviarfoto);

		foto.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				boolean internet = isInternetConnectionActive(ExhibicionSup.this);
				if (internet == true){
				
				Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);  
//				File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
				File file = new File(Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nombrefoto);

				Uri outputFileUri = Uri.fromFile(file);
				cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
				Log.i("URI PHOTO", outputFileUri.toString());
				startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  
		    	}else if(internet == false){
		            AlertDialog alertdialog=new AlertDialog.Builder(ExhibicionSup.this).create();
					alertdialog.setIcon(R.drawable.icon);
			    	alertdialog.setTitle("Aviso");
			    	alertdialog.setMessage("Error de conectividad");
			    	alertdialog.show();
				}
			}
		});
		
		}else if(internet == false){
            AlertDialog alertdialog=new AlertDialog.Builder(ExhibicionSup.this).create();
			alertdialog.setIcon(R.drawable.icon);
	    	alertdialog.setTitle("Aviso");
	    	alertdialog.setMessage("Error de conectividad");
	    	alertdialog.show();
		}
		
		

	}
	
	protected LoginSitesList mostrarRetail() {
		LoginSitesList loginsitesList = null;
			try {
				SharedPreferences prefs =
					     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
				
				String idcia= prefs.getString("idcia", "0");
				/** Handling XML */
				spf = SAXParserFactory.newInstance();
				sp = spf.newSAXParser();
				xr = sp.getXMLReader();
	

				URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?" +
						"Query=select+a.*+from+alsellm_admdisney..CatExhibicion+a+inner+join+exhibiciones_cadenas+b+"+
						"on+a.idexhibicion=b.idexhibicion+inner+join+cliente+c+on+b.cadena=c.cadena+"+
						"where+c.idcliente="+idCliente+"+and+a.idcia="+idcia+"+and+a.TipoExhibicion+='RETAIL'");
				
				Log.i("MII TAGG", ""+sourceUrl);
	
				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
				xr.setContentHandler(myXMLHandler);
				//xr.parse(new InputSource(sourceUrl.openStream()));
				InputSource input= new InputSource(sourceUrl.openStream());
				input.setEncoding("utf-8");
				xr.parse(input);
				
			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}
			loginsitesList = LoginMyXMLHandler.loginsitesList;
		return loginsitesList;			
	}
	
	protected LoginSitesList mostrarMuebles() {
		LoginSitesList loginsitesList = null;
			try {
				SharedPreferences prefs =
					     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
				
				String idcia= prefs.getString("idcia", "0");
				/** Handling XML */
				spf = SAXParserFactory.newInstance();
				sp = spf.newSAXParser();
				xr = sp.getXMLReader();
	
//				/** Send URL to parse XML Tags */
//				URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?" +
//						"Query=select+*+from+alsellm_admdisney..catexhibicion+where+idcia="+idcia+"+and+tipoexhibicion='VIDEO'");
				URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?" +
						"Query=select+a.*+from+alsellm_admdisney..CatExhibicion+a+inner+join+exhibiciones_cadenas+b+"+
						"on+a.idexhibicion=b.idexhibicion+inner+join+cliente+c+on+b.cadena=c.cadena+"+
						"where+c.idcliente="+idCliente+"+and+a.idcia="+idcia+"+and+a.TipoExhibicion+='VIDEO'");
				
				
				Log.i("MII TAGG", ""+sourceUrl);
	
				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
				xr.setContentHandler(myXMLHandler);
				//xr.parse(new InputSource(sourceUrl.openStream()));
				InputSource input= new InputSource(sourceUrl.openStream());
				input.setEncoding("utf-8");
				xr.parse(input);
				
			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}
			loginsitesList = LoginMyXMLHandler.loginsitesList;
		return loginsitesList;			
	}
	
	protected LoginSitesList mostrarConsumo() {
		LoginSitesList loginsitesList = null;
			try {
				SharedPreferences prefs =
					     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
				
				String idcia= prefs.getString("idcia", "0");
				/** Handling XML */
				spf = SAXParserFactory.newInstance();
				sp = spf.newSAXParser();
				xr = sp.getXMLReader();
	
				
				URL sourceUrl = new URL(urlamentretenimiento+"AMEntretenimiento/DataServlet?" +
						"Query=select+a.*+from+alsellm_admdisney..CatExhibicion+a+inner+join+exhibiciones_cadenas+b+"+
						"on+a.idexhibicion=b.idexhibicion+inner+join+cliente+c+on+b.cadena=c.cadena+"+
						"where+c.idcliente="+idCliente+"+and+a.idcia="+idcia+"+and+a.TipoExhibicion+='CONSUMO'");
				
				Log.i("MII TAGG", ""+sourceUrl);
	
				/** Create handler to handle XML Tags ( extends DefaultHandler ) */
				LoginMyXMLHandler myXMLHandler = new LoginMyXMLHandler();
				xr.setContentHandler(myXMLHandler);
				//xr.parse(new InputSource(sourceUrl.openStream()));
				InputSource input= new InputSource(sourceUrl.openStream());
				input.setEncoding("utf-8");
				xr.parse(input);
				
			} catch (Exception e) {
				System.out.println("XML Pasing Excpetion = " + e);
			}
			loginsitesList = LoginMyXMLHandler.loginsitesList;
		return loginsitesList;			
	}
	
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if(resultCode==RESULT_CANCELED){
	    	Toast.makeText(getApplicationContext(), "No se ha tomado la foto", Toast.LENGTH_LONG).show();

		}
		else{
		    if (requestCode == CAMERA_PIC_REQUEST) {
		    	
		    	
		    	BitmapFactory.Options options = new BitmapFactory.Options();
		    	options.inSampleSize = 2;    // this will cut the sampling by 50% PARA MOTOROLA
//		    	options.inSampleSize = 4;    // this will cut the sampling by 50% PARA XPERIA
		    	
				imageInSD = Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nombrefoto;

		    	
		    	Bitmap bmap = BitmapFactory.decodeFile(imageInSD,options);
		    	int width = bmap.getWidth();
		        int height = bmap.getHeight();
		        Log.i("Ancho de archivo", ""+width);
		        Log.i("Alto de archivo", ""+height);
		        int newWidth;
		        int newHeight;
		        if(width < height){
		        	  newWidth = 600;
				         newHeight =800 ;
		        }else{
		        	  newWidth = 800;
				         newHeight = 600;
		        }
		        float scaleWidth = ((float) newWidth) / width;
		        float scaleHeight = ((float) newHeight) / height;
		     // createa matrix for the manipulation
		        Matrix matrix = new Matrix();
		        // resize the bit map
		        matrix.postScale(scaleWidth, scaleHeight);
		        
		    	
				if(orientation <= 45 || (orientation> 315 && orientation<360)){
					matrix.postRotate(90);
				}else{
					matrix.postRotate(0);
				}
				
				
//		        matrix.postRotate(0);
		     // recreate the new Bitmap
		         bm = Bitmap.createBitmap(bmap, 0, 0,
		                          width, height, matrix, true);
		    	Log.i("Bitmap getWidth", ""+bm.getWidth());
		    	Log.i("Bitmap getHeight", ""+bm.getHeight());
		    	 int newWidth2,newHeight2;
			        if(bm.getWidth() < bm.getHeight()){
			        	  newWidth2 = 135;
					      newHeight2 = 181;
			        }else{
			        	  newWidth2 = 181;
					      newHeight2 = 135;

			        }
			        float scaleWidth2 = ((float) newWidth2) / width;
			        float scaleHeight2 = ((float) newHeight2) / height;
		    	 // createa matrix for the manipulation
		        Matrix matrix2 = new Matrix();
		        // resize the bit map
		        matrix2.postScale(scaleWidth2, scaleHeight2);
//		        matrix.postRotate(0);
		     // recreate the new Bitmap
		        Bitmap bmapa = Bitmap.createBitmap(bmap, 0, 0,
		                          width, height, matrix2, true);
		        dialog=new Dialog(this);
		    	dialog.setContentView(R.layout.custom_dial);
		    	dialog.setTitle("¿ Es correcta la foto ?");
		    	ImageView image = (ImageView) dialog.findViewById(R.id.imageView1);  
		    	image.setImageBitmap(bmapa); 
		    	dialog.show();
		    	Button botonina = (Button) dialog.findViewById(R.id.button1);

		    	botonina.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						boolean internet = isInternetConnectionActive(ExhibicionSup.this);
						if (internet == true){
					dialog.cancel();
					dialog.dismiss();
									progreso();
						}else if(internet == false){
				            AlertDialog alertdialog=new AlertDialog.Builder(ExhibicionSup.this).create();
							alertdialog.setIcon(R.drawable.icon);
					    	alertdialog.setTitle("Aviso");
					    	alertdialog.setMessage("Error de conectividad");
					    	alertdialog.show();
						}
					}
				});
		    	
		    	Button botootra = (Button) dialog.findViewById(R.id.button2);
		    	botootra.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						dialog.dismiss();
						dialog.cancel();
						Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);  
//						File file = new File(Environment.getExternalStorageDirectory(), "test.jpg");
						File file = new File(Environment.getExternalStorageDirectory()+"/AMEntretenimiento/"+nombrefoto);

						Uri outputFileUri = Uri.fromFile(file);
						cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

						 
						Log.i("URI PHOTO", outputFileUri.toString());
						startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  
						
						
					}
				});
		    	

		    }

	    }
	}
	
	public void executeMultipartPost() throws Exception {
		try {
			
			Calendar mical=Calendar.getInstance();
			String fec=""+mical.get(Calendar.DAY_OF_MONTH)+"-"+(mical.get(Calendar.MONTH)+1)+"-"+mical.get(Calendar.YEAR);
			hora=""+mical.get(Calendar.HOUR_OF_DAY)+"-"+mical.get(Calendar.MINUTE)+"-"+mical.get(Calendar.SECOND);
			
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			bm.compress(Bitmap.CompressFormat.JPEG, 50, bos);
		
			byte[] data = bos.toByteArray();
			HttpClient httpClient = new DefaultHttpClient();
			
			HttpPost postRequest = new HttpPost(urlamentretenimiento+"AMEntretenimiento/UploadServlet");
			SharedPreferences prefs =
				     getSharedPreferences("MisPreferencias",Context.MODE_PRIVATE);
			
			String nomtiendacod = remove1(prefs.getString("nombre", "nulo"));	
			Log.i("CADENACODIF", ""+nomtiendacod);
			
			bab = new ByteArrayBody(data, nomtiendacod.toUpperCase()+fec+"_"+hora+".jpeg");
			Log.i("NOMBRE FOTO", nomtiendacod.toUpperCase()+fec+"_"+hora+".jpeg");
			
//			bab = new ByteArrayBody(data, fec+"_"+hora+".png");
//			Log.i("NOMBRE FOTO", fec+"_"+hora+".png");
			// File file= new File("/mnt/sdcard/forest.png");
			// FileBody bin = new FileBody(file);
			MultipartEntity reqEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			
			//Pasar los parametros 
			reqEntity.addPart("uploaded", bab);
			reqEntity.addPart("tipo", new StringBody("E"));
			

			
			String idcia= prefs.getString("idcia", "0");
			reqEntity.addPart("idcia", new StringBody(""+idcia));
			reqEntity.addPart("idagente", new StringBody(""+prefs.getString("idagente", "nulo")));
			reqEntity.addPart("idcliente",  new StringBody(""+idCliente));
			
			if(spinnerconsumo.isEnabled()){
				reqEntity.addPart("idexhibicion", new StringBody(""+idexhibicion2));

			}else if(spinnervideo.isEnabled()){
				reqEntity.addPart("idexhibicion", new StringBody(""+idexhibicion));

			}
		else if(spinnerretail.isEnabled()){
			reqEntity.addPart("idexhibicion", new StringBody(""+idexhibicion3));

		}
			
//			reqEntity.addPart("idexhibicion", new StringBody(""+idexhibicion));
			
//			reqEntity.addPart("photoCaption", new StringBody("sfsdfsdf"));
			postRequest.setEntity(reqEntity);
			HttpResponse response = httpClient.execute(postRequest);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			String sResponse;
			StringBuilder s = new StringBuilder();

			while ((sResponse = reader.readLine()) != null) {
				s = s.append(sResponse);
			}
			System.out.println("Response: " + s);
			
			signal3g=1;
			handler.sendEmptyMessage(0);

		} catch (Exception e) {
			// handle exception here
			Log.e(e.getClass().getName(), e.getMessage());
		}

	}

	@Override
	public void run() {
		try {
			executeMultipartPost();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	protected void progreso() {
		// TODO Auto-generated method stub
//		pd = ProgressDialog.show(this, "Espere por favor", "Cargando..", true, false);
pd = ProgressDialog.show(this, "Espere por favor", "Cargando..", true, true, new DialogInterface.OnCancelListener() {
			
			@Override
			public void onCancel(DialogInterface dialog) {
				onBackPressed();
			}
		});
		Thread thread = new Thread(this);
		thread.start();
//		Timer timer=new Timer();
//		timer.schedule(new TimerTask() {
//			
//			@Override
//			public void run() {
//
//				if(signal3g==1){					//Significa que termino el proceso satisfactoriamente
//					Log.i("Ejecuta el Timer", "NO Cancelamos el progress dialog");
//					signal3g=0;
//
//				}else{
//					Log.i("Ejecuta el Timer", "Cancelamos el progress dialog");
//
//					pd.dismiss();
//					pd.cancel();
//				}
//			}
//		}, 120000);
	}
	
	private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	Log.i("MIHORA", hora);
       
                pd.dismiss();
                Toast.makeText(getApplicationContext(), "Envío de archivo terminado", Toast.LENGTH_LONG).show();
                
                
 
        }
	};
	
	public static boolean isInternetConnectionActive(Context context) {
		 boolean bool = false;

		   NetworkInfo networkInfo = ((ConnectivityManager) context
                 .getSystemService(Context.CONNECTIVITY_SERVICE))
                 .getActiveNetworkInfo();

               if(networkInfo == null || !networkInfo.isConnected()) {
                return false;
               }
               return true;
	}
	
	public static String remove1(String input) {
        // Cadena de caracteres original a sustituir.
		String original = "áàäéèëíìïóòöúùuñÁÀÄÉÈËÍÌÏÓÒÖÚÙÜÑçÇ";		// Cadena de caracteres ASCII que reemplazar�n los originales.
		String ascii = "aaaeeeiiiooouuunAAAEEEIIIOOOUUUNcC";
        String output = input;
        for (int i=0; i<original.length(); i++) {
            // Reemplazamos los caracteres especiales.
            output = output.replace(original.charAt(i), ascii.charAt(i));
        }//for i
        return output;
    }//remove1
	
	
	
}
